import { createRouter, createWebHashHistory } from "vue-router"; //
import { getToken } from "@/utils/storage";
import { ElMessage } from "element-plus";
const router = createRouter({
  // 使用hash模式
  history: createWebHashHistory(), // 修改这里，移除BASE_URL参数
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/index.vue"),
      meta: {
        title: "登录",
        requiresAuth: false,
      },
    },
    {
      path: "/",
      component: () => import("@/views/layout/index.vue"),
      redirect: "/home",
      meta: {
        title: "首页",
        requiresAuth: true,
      },
      children: [
        {
          path: "home",
          component: () => import("@/views/home/index.vue"),
          meta: { title: "首页", requiresAuth: true },
        },
        {
          path: "goods",
          component: () => import("@/views/goods/index.vue"),
          meta: { title: "商品管理", requiresAuth: true },
        },
        {
          path: "user",
          component: () => import("@/views/client/index.vue"),
          meta: { title: "用户管理", requiresAuth: true },
        },
        {
          path: "other",
          component: () => import("@/views/other/index.vue"),
          meta: { title: "其他管理", requiresAuth: true },
        },
      ],
    },
    {
      path: "/404",
      component: () => import("@/views/notFound/index.vue"),
      meta: {
        title: "未找到",
        requiresAuth: false,
      },
    },
    // 任意未匹配到的路径 都重定向到404
    {
      path: "/:pathMatch(.*)*",
      redirect: "/404",
    },
  ],
});
// // 路由前置守卫
// 辅助函数
const checkAuth = (to, token) => {
  const needAuth = to.matched.some(r => r.meta?.requiresAuth)
  const isLoginPage = to.path === '/login'
// 未登录且需要登录的情况
  if (needAuth && !token) {
    ElMessage.error("请先登录")
    return '/login'
  }
  // 已登录且访问登录页的情况
  if (token && isLoginPage) {
    ElMessage.warning('您已登录，请勿重复登录')
    return '/'
  }

  return null // 放行
}

router.beforeEach((to, from, next) => {
  to.meta?.title && (document.title = to.meta.title)

  const token = getToken()
  const redirect = checkAuth(to, token)

  next(redirect || undefined)
})
export default router;
